﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using FurionApiDemo.Core.Const;
using FurionApiDemo.Core.Entity;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FurionApiDemo.Core.Manager.User
{
    public class UserManager : IUserManager, IScoped
    {
        private readonly IRepository<SysUser> _sysUserRep; // 用户表仓储   
        private readonly IRepository<SysUserInfo> _sysUserInfoRep; // 用户表仓储   
        private readonly IHttpContextAccessor _httpContextAccessor;

        public UserManager(IRepository<SysUser> sysUserRep,
                           IRepository<SysUserInfo> sysUserInfoRep,
                           IHttpContextAccessor httpContextAccessor)
        {
            _sysUserRep = sysUserRep;
            _sysUserInfoRep = sysUserInfoRep;
            _httpContextAccessor = httpContextAccessor;
        }

        public long UserId
        {
            get => long.Parse(_httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
        }

        public string Account
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_USER_NAME)?.Value;
        }

        public string Name
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_NAME)?.Value;
        }

        public bool SuperAdmin
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == ((int)AdminType.SuperAdmin).ToString();
        }

        public bool Admin
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == ((int)AdminType.Admin).ToString();
        }

        public SysUser User
        {
            get => _sysUserRep.Find(UserId);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tracking"></param>
        /// <returns></returns>
        public async Task<SysUser> CheckUserAsync(long userId, bool tracking = true)
        {
            var user = await _sysUserRep.FirstOrDefaultAsync(u => u.Id == userId, tracking);
            //user.SysUserInfo = await _sysUserInfoRep.FirstOrDefaultAsync(u => u.Id == userId, tracking);
            return user ?? throw Oops.Oh(ErrorCode.D1002);
        }

        /// <summary>
        /// 获取用户详情信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tracking"></param>
        /// <returns></returns>
        public async Task<SysUserInfo> CheckUserInfoAsync(long userId, bool tracking = true)
        {
            var userInfo = await _sysUserInfoRep.FirstOrDefaultAsync(u => u.UserId == userId, tracking);
            return userInfo ?? throw Oops.Oh(ErrorCode.D1002);
        }
    }
}
